<template>
</template>

<script>
/* ============
* Axios
* ============
*
* Promise based HTTP client for the browser and node.js.
* Because Vue Resource has been retired, Axios will now been used
* to perform AJAX-requests.
*
* https://github.com/mzabriskie/axios
*/

import Vue from "vue";
import Axios from "axios";
import store from "@/store";

// Axios.defaults.baseURL = process.env.API_LOCATION;
Axios.defaults.baseURL = "/frontend/v1/";
Axios.defaults.headers.common.Accept = "application/json";

function getCookie(name) {
  const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
  const arr = document.cookie.match(reg);
  if (arr) {
    return unescape(arr[2]);
  }
  return null;
}

Axios.interceptors.request.use(
  config => {
    let userinfo = getCookie("userinfo");
    if (userinfo) {
      userinfo = JSON.parse(userinfo);
      localStorage.setItem("id_token", userinfo.token);
      store.commit("common/LOGIN_USER", userinfo);
    }
    // 判断是否存在id_token，有则放入http头一起请求
    if (localStorage.getItem("id_token")) {
      config.headers.Authorization = `Bearer ${localStorage.getItem(
        "id_token"
      )}`;
    }
    if (getCookie("csrfToken")) {
      config.headers["x-csrf-token"] = getCookie("csrfToken");
    }
    return config;
  },
  err => Promise.reject(err)
);

Axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      store.dispatch("user/logout");
    }
    if (error.response.status === 400) {
      store.commit("common/NEWDIALOG", [true, error.response.data.message]);
    }
    return Promise.reject(error);
  }
);

// Bind Axios to Vue.
Vue.$http = Axios;
Object.defineProperty(Vue.prototype, "$http", {
  get() {
    return Axios;
  }
});

export default {
  name: "HelloWorld",
  data() {
    return {};
  }
};
</script>

<style scoped>
</style>
